package com.example.hcd.functionactivity;

import java.io.File;
import java.util.ArrayList;

import com.example.logic.ImgFileListActivity;
import com.example.hcd.R;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.internet.FileUtils;
import com.example.hcd.tool.ToastHelp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * @author spring sky<br>
 *         Email :vipa1888@163.com<br>
 *         QQ: 840950105<br>
 * @version 创建时间：2012-11-22 上午9:20:03 说明：主要用于选择文件操作
 */

public class SelectPicActivity extends BaseActivity implements OnClickListener {

	/***
	 * 使用照相机拍照获取图片
	 */
	public static final int SELECT_PIC_BY_TACK_PHOTO = 1;
	/***
	 * 使用相册中的图片
	 */
	public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
	/***
	 * 使用相册中的图片
	 */
	public static final int SELECT_FILE_BY_PICK_FILES = 3;

	/***
	 * 从Intent获取图片路径的KEY
	 */
	public static final String KEY_PHOTO_PATH = "files";

	private static final String TAG = "SelectPicActivity";

	private LinearLayout dialogLayout;
	private Button takePhotoBtn, pickPhotoBtn, cancelBtn;

	/** 获取到的图片路径 */
	private String picPath;

	private Intent lastIntent;

	private Uri photoUri;
	// 是选择多项 choosemore 选择一项chooseone
	private String type;

	private boolean isChooseFile =false;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_pic_layout);
		mPageName = "SelectPicActivity";
		isChooseFile = getIntent().getBooleanExtra("IS_CHOOSE_FILE", isChooseFile);
		
		UserInfo.getUserInfor().isUsePhoto = true;
		
		initView();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub if(keyCode == KeyEvent.KEYCODE_BACK){
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			
			UserInfo.getUserInfor().isUsePhoto = false;
			finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	}

	/**
	 * 初始化加载View
	 */
	private void initView() {
		dialogLayout = (LinearLayout) findViewById(R.id.dialog_layout);
		dialogLayout.setOnClickListener(this);
		takePhotoBtn = (Button) findViewById(R.id.btn_take_photo);
		takePhotoBtn.setOnClickListener(this);
		pickPhotoBtn = (Button) findViewById(R.id.btn_pick_photo);
		pickPhotoBtn.setOnClickListener(this);
		cancelBtn = (Button) findViewById(R.id.btn_cancel);
		cancelBtn.setOnClickListener(this);

		lastIntent = getIntent();
		type = lastIntent.getStringExtra("type");
		
		if(isChooseFile)
		{
			Button pickFile = (Button) findViewById(R.id.btn_pick_file);
			pickFile.setVisibility(View.VISIBLE);
			pickFile.setOnClickListener(this);
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.dialog_layout:
			UserInfo.getUserInfor().isUsePhoto = false;
			finish();
			break;
		case R.id.btn_take_photo:
			takePhoto();
			break;
		case R.id.btn_pick_photo:
			pickPhoto();
			break;
		case R.id.btn_pick_file:
			pickFiles();
			break;
		default:
			UserInfo.getUserInfor().isUsePhoto = false;
			finish();
			break;
		}
	}

	/**
	 * 拍照获取图片
	 */
	private void takePhoto() {
		// 执行拍照前，应该先判断SD卡是否存在
		String SDState = Environment.getExternalStorageState();
		if (SDState.equals(Environment.MEDIA_MOUNTED)) {

			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// "android.media.action.IMAGE_CAPTURE"
			/***
			 * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
			 * 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
			 */
			ContentValues values = new ContentValues();
			photoUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
			intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
			/** ----------------- */
			startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
		} else {
			Toast.makeText(this, "内存卡不存在", Toast.LENGTH_LONG).show();
		}
//		String SDState = Environment.getExternalStorageState();
//		if (SDState.equals(Environment.MEDIA_MOUNTED)) {
//		Intent intent = new Intent();
//        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//        File f = getFile();
//        File mPhotoCache;
//        if (f == null) {
//            Toast.makeText(this, "获取文件错误", Toast.LENGTH_SHORT).show();
//            return;
//        } else {
//            mPhotoCache = new File(f, System.currentTimeMillis() + ".jpg");
//        }
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoCache));
//        
//        startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
//		} else {
//			Toast.makeText(this, "内存卡不存在", Toast.LENGTH_LONG).show();
//		}
	}
	
	private File getFile() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // �ļ�����ʹ���ⲿ�洢
            File f = new File(Environment.getExternalStorageDirectory(), "venadaOA");
            if (!f.exists()) {
                f.mkdirs();
            }
            return f;
        } else if ((new File("/mnt/sdcard2")).exists()) { // ������ֻ���������V955,�洢��Ϊsdcard2
            String file = "/mnt/sdcard2/" + "venadaOA";
            File f = new File(file);
            if (!f.exists()) {
                f.mkdirs();
            }
            return f;
        }
        return null;
    }

	/***
	 * 从相册中取图片
	 */
	private void pickPhoto() {

		if (type.equals("chooseone")) {
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_PICK);
			startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
		} else if (type.equals("choosemore")) {
			Intent intent = new Intent(SelectPicActivity.this, ImgFileListActivity.class);
			startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
			overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);
		}
		// startActivityForResult(createDefaultOpenableIntent(), 10);

	}

	/** 选择文件 */
	private void pickFiles() {
		
//		Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//		i.addCategory(Intent.CATEGORY_OPENABLE);
//		i.putExtra(Intent.EXTRA_TITLE, "选择文件");
//		i.setType("video/mp4");
		Intent fileChooserIntent =  new Intent(this , 
				FileChooserActivity.class);
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
			try {
				startActivityForResult(fileChooserIntent, SELECT_FILE_BY_PICK_FILES);
			} catch (android.content.ActivityNotFoundException ex) {
				Toast.makeText(this, "亲，木有文件管理器啊-_-!!", Toast.LENGTH_SHORT).show();
			}
    	else
    		Toast.makeText(this, "亲，没有内存卡-_-!!", Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		finish();
		return super.onTouchEvent(event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			UserInfo.getUserInfor().isUsePhoto = false;
			if (type.equals("chooseone")) {
				doPhoto(requestCode, data);
			} else if (type.equals("choosemore")) {
				if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
					ArrayList<String> picPaths = data.getStringArrayListExtra(KEY_PHOTO_PATH);
					lastIntent.putStringArrayListExtra(KEY_PHOTO_PATH, picPaths);
					setResult(Activity.RESULT_OK, lastIntent);
					finish();
				} else if (requestCode == SELECT_PIC_BY_TACK_PHOTO) {
					doPhoto(requestCode, data);
				} else if (requestCode == SELECT_FILE_BY_PICK_FILES) {
//					if (data == null) {
//						//Toast.makeText(this, "选择文件出错", Toast.LENGTH_LONG).show();
//						ToastHelp.doToast(this,  "选择文件出错");
//						return;
//					}
//					photoUri = data.getData();
//					if (photoUri == null) {
//						ToastHelp.doToast(this,  "选择文件出错");
//						return;
//					}
					picPath = data.getStringExtra(KEY_PHOTO_PATH);
					 
					
					// Get the Uri of the selected file
					//picPath = getRealPath(photoUri);

					if (picPath != null) {
						
						if(isInMyType(picPath))
						{
							ArrayList<String> picPaths = new ArrayList<String>();
							picPaths.add(picPath);
							lastIntent.putStringArrayListExtra(KEY_PHOTO_PATH, picPaths);
							setResult(Activity.RESULT_OK, lastIntent);
							finish();
						}else
						{
							//Toast.makeText(this, "文件不支持", Toast.LENGTH_LONG).show();
							ToastHelp.doToast(this,  "文件不支持");
						}
						
						
					} else {
						ToastHelp.doToast(this,  "选择文件出错");
					}
				}
			}

		}

	}

	@SuppressLint("NewApi")
	private String getRealPath(Uri fileUrl) {
		String fileName = null;
		Uri filePathUri = fileUrl;
		if (fileUrl != null) {
			if (filePathUri.getScheme().compareTo("file") == 0) // file:///开头的uri
			{
				fileName =Uri.decode(filePathUri.toString());
				fileName =fileName.replace("file:///", "");
				// 替换file://
//				if (!fileName.startsWith("/mnt")) {
//					// 加上"/mnt"头
//					fileName = "/mnt" + fileName;
//				}
			}else if(filePathUri.getScheme().compareTo("content") == 0)
			{
				final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; 
				if (isKitKat && DocumentsContract.isDocumentUri(this, filePathUri)) {  
			        // ExternalStorageProvider  
			        if (isExternalStorageDocument(filePathUri)) {  
			            final String docId = DocumentsContract.getDocumentId(filePathUri);  
			            final String[] split = docId.split(":");  
			            final String type = split[0];  
			  
			            if ("primary".equalsIgnoreCase(type)) {  
			            	fileName = Environment.getExternalStorageDirectory() + "/" + split[1];  
			            }  
			  
			            // TODO handle non-primary volumes  
			        }  
			        // DownloadsProvider  
			        else if (isDownloadsDocument(filePathUri)) {  
			  
			            final String id = DocumentsContract.getDocumentId(filePathUri);  
			            final Uri contentUri = ContentUris.withAppendedId(  
			                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));  
			  
			            fileName =  getDataColumn(this, contentUri, null, null);  
			        }  
			        // MediaProvider  
			        else if (isMediaDocument(filePathUri)) {  
			            final String docId = DocumentsContract.getDocumentId(filePathUri);  
			            final String[] split = docId.split(":");  
			            final String type = split[0];  
			  
			            Uri contentUri = null;  
			            if ("image".equals(type)) {  
			                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;  
			            } else if ("video".equals(type)) {  
			                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;  
			            } else if ("audio".equals(type)) {  
			                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
			            }  
			  
			            final String selection = "_id=?";  
			            final String[] selectionArgs = new String[] {  
			                    split[1]  
			            };  
			  
			            fileName = getDataColumn(this, contentUri, selection, selectionArgs);  
			        }  
			    }  
			    // MediaStore (and general)  
			    else if ("content".equalsIgnoreCase(filePathUri.getScheme())) {  
			    	fileName = getDataColumn(this, filePathUri, null, null);  
			    }  
			    // File  
			    else if ("file".equalsIgnoreCase(filePathUri.getScheme())) {  
			    	fileName =  filePathUri.getPath();  
			    }
				
			}
		}
		return fileName;
	}
	
	public static String getDataColumn(Context context, Uri uri, String selection,  
	        String[] selectionArgs) {  
	  
	    Cursor cursor = null;  
	    final String column = "_data";  
	    final String[] projection = {  
	            column  
	    };  
	  
	    try {  
	        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,  
	                null);  
	        if (cursor != null && cursor.moveToFirst()) {  
	            final int column_index = cursor.getColumnIndexOrThrow(column);  
	            return cursor.getString(column_index);  
	        }  
	    } finally {  
	        if (cursor != null)  
	            cursor.close();  
	    }  
	    return null;  
	}  
	  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is ExternalStorageProvider. 
	 */  
	public static boolean isExternalStorageDocument(Uri uri) {  
	    return "com.android.externalstorage.documents".equals(uri.getAuthority());  
	}  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is DownloadsProvider. 
	 */  
	public static boolean isDownloadsDocument(Uri uri) {  
	    return "com.android.providers.downloads.documents".equals(uri.getAuthority());  
	}  
	  
	/** 
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is MediaProvider. 
	 */  
	public static boolean isMediaDocument(Uri uri) {  
	    return "com.android.providers.media.documents".equals(uri.getAuthority());  
	}

	/**
	 * 选择图片后，获取图片的路径
	 * 
	 * @param requestCode
	 * @param data
	 */
	private void doPhoto(int requestCode, Intent data) {
		if (requestCode == SELECT_PIC_BY_PICK_PHOTO) // 从相册取图片，有些手机有异常情况，请注意
		{
			if (data == null) {
				//Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
				ToastHelp.doToast(this,  "选择图片文件出错");
				return;
			}
			photoUri = data.getData();
			if (photoUri == null) {
				//Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
				ToastHelp.doToast(this,  "选择图片文件出错");
				return;
			}
		}
		String[] pojo = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
		if (cursor != null) {
			int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
			cursor.moveToFirst();
			picPath = cursor.getString(columnIndex);
			cursor.close();
		}

		if (picPath != null && (FileUtils.isPic(picPath))) {
			ArrayList<String> picPaths = new ArrayList<String>();
			picPaths.add(picPath);
			lastIntent.putStringArrayListExtra(KEY_PHOTO_PATH, picPaths);
			setResult(Activity.RESULT_OK, lastIntent);
			finish();
		} else {
			//Toast.makeText(this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
			ToastHelp.doToast(this,  "选择图片文件出错");
		}
	}
	//目前支持上传的格式
	public static String[] typelist = {".png",".PNG",".JPG",".jpg",".txt",".doc",".zip",".pdf",".xls",".XLS"};
	
	private boolean isInMyType(String name)
	{
		return true;
//		for(String type:typelist)
//		{
//			if(name.contains(type))
//			{
//				return true;
//			}
//		}
//		
//		return false;
	}
}
